import medicationService from '../services/medication.js';
import Result from '../utils/result.js';

const medicationController = {
     async getMedications (req, res) {
        try {
            const {userId} = req.params;
            const {allergy} = req.query;
            if(!userId){
                return res.status(400).json(Result.badRequest('userId不能为空'));
            }
            
            const medications = await medicationService.getMedications(userId,allergy);

            return res.status(200).json(medications);
        } catch (error) {
            console.error(error);
            return res.status(500).json(error);
        }
    },
     async addMedication  (req, res)  {
        try {
            const data =  req.body;
            if(!data.userId || !data.medicationName){
                return res.status(400).json(Result.badRequest('userId和medicationName不能为空'));
            }
            
            const result = await medicationService.addMedication(data);

            return res.status(200).json(result);
        }catch (error) { 
            console.error(error);
            return res.status(500).json(Result.error('添加用药记录失败'));
        }
    },
     async delMedication(req, res)  {
        try {
            const {medicationId,userId} = req.body;
            if(!medicationId){
                return res.status(400).json(Result.badRequest('medicationId不能为空'));
            }
            if(!userId){
                return res.status(400).json(Result.badRequest('userId不能为空'));
            }
            const result = await medicationService.delMedication(medicationId,userId);
            return res.status(200).json(result);
        }catch (error) { 
            console.error(error);
            return res.status(500).json(Result.error('删除用药记录失败'));
        }
    },

};

export default medicationController;
